import React, { Component } from 'react';
import { connect } from 'react-redux';
import { add, asyncAdd } from '../../redux/actions/count';

class CountUI extends Component {
  state = ({
    count: 0
  })

  handleAdd = () => {
    const { value } = this.getSelectRef;
    // const { count } = this.state;

    this.props.add(value * 1);

    // this.setState({
    //   count: count + value * 1
    // })
  }

  handleAsyncAdd = () => {
    const { value } = this.getSelectRef;
    /* 当setState参数是对象的时候，需要从state身上拿count值 */ 
    // const { count } = this.state;

    this.props.asyncAdd(value * 1, 1000)

    // setTimeout(() => {
    //   /* setState写法一：参数是对象 */ 
    //   // this.setState({
    //   //   count: count + value * 1
    //   // })

    //   /* setState写法二：参数是函数 */ 
    //   this.setState(state => {
    //     return {
    //       count: state.count + value * 1
    //     }
    //   })
    // }, 1000);
  }

  render() {
    return (
      <div>
        <h1>组件Count</h1>
        <h4>count值：{ this.props.count }</h4>
        <select ref={ c => this.getSelectRef = c } placeholder="请选择">
          <option value="1">1</option>
          <option value="2">2</option>
          <option value="3">3</option>
        </select>
        <button onClick={ this.handleAdd }>同步+加</button>
        <button onClick={ this.handleAsyncAdd }>异步+加</button>
      </div>
    )
  }
}

export default  connect(state => {
  return {
    count: state.count
  }
}, {
  add,
  asyncAdd
})(CountUI);